﻿/*
** nopCommerce ajax cart implementation
*/
var cartclosetimeout;
var carthighlighttimeout;
var popoverdestroytimeout;

var AjaxCart = {
    //loadWaiting: false,
    usepopupnotifications: false,
    topcartselector: '',
    topwishlistselector: '',
    flyoutcartselector: '',
    flyoutwishlistselector: '',

    init: function (usepopupnotifications, topcartselector, topwishlistselector, flyoutcartselector, flyoutwishlistselector) {
        this.usepopupnotifications = usepopupnotifications;
        this.topcartselector = topcartselector;
        this.topwishlistselector = topwishlistselector;
        this.flyoutcartselector = flyoutcartselector;
        this.flyoutwishlistselector = flyoutwishlistselector;
    },

    addproducttocart: function (url, productid, element, qty) {
        $('#cart-message').popover("destroy");
        var quantity = 1;
        var qtyelement = element.parent().find("input.quantity");
        if (qtyelement.length && !isNaN(parseInt(qtyelement.val())) && parseInt(qtyelement.val()) >= 1) {
            quantity = parseInt(qtyelement.val());
        }
        var loading = element.parent().find(".product-add-loading");
        loading.show();
        element.hide();
        $.ajax({
            cache: false,
            url: url,
            data: {path: window.location.pathname, quantity : quantity},
            type: 'post',
            success: function (data, textStats, jqXHR) {
                AjaxCart.successprocess(data, textStats, jqXHR, "add", productid, element);
            },
            error: function (data, textStats, jqXHR) {
                AjaxCart.ajaxFailure(data, textStats, jqXHR, "add", productid, element);
            }
        }).always(function () {
            var addloadingelement = element.closest(".panel-small").find(".addproduct-loading");
            if (addloadingelement.length) {
                addloadingelement.fadeOut(200, function () {
                    $(this).remove();
                });
            }
            loading.hide();
            element.show();
        });
    },

    reserveproductvariant: function (url, form, elem) {
        $('#cart-message').popover("destroy");
        var d = form.serializeArray();
        $.ajax({
            cache: false,
            url: url,
            data: d,
            type: 'post',
            success: function (data) {
                if (data.success) {
                    form.find(".product-loading").hide();
                    window.location.href = data.redirect;
                }
            },
            error: function (data) {
            }
        });
    },

    addproductvarianttocart: function (url, form, elem) {
        $('#cart-message').popover("destroy");
        form.find(".product-loading").show();
        var d = form.serializeArray();
        if (typeof dircheck != "undefined" && (dircheck == true || dircheck == "True")) {
            d.push({name: 'directCheckout', value: true});
        }
        if (typeof bypasscart != "undefined" && (bypasscart == true || bypasscart == "True")) {
            d.push({ name: 'bypassCart', value: true });
        }
        var loading = elem.parent().find(".product-add-loading");
        loading.show();
        elem.hide();
        $.ajax({
            cache: false,
            url: url,
            data: d,
            type: 'post',
            success: function (data, textStats, jqXHR) {
                form.find(".product-loading").hide();
                if (typeof data.prompt != "undefined") {
                    $("#direct-checkout .modal-body").html(data.prompt);
                    $("#direct-checkout").modal("show");
                    $("#direct-checkout .no").click(function () {
                        $("#direct-checkout").modal("hide");
                    });
                    $("#direct-checkout .yes").click(function () {
                        $("#direct-checkout").modal("hide");
                        AjaxCart.addproductvarianttocart(url, form, elem, true, true);
                    });
                } else {
                    AjaxCart.successprocess(data, textStats, jqXHR, "add", null);
                }
            },
            error: function (data, textStats, jqXHR) {
                form.find(".product-loading").hide();
                AjaxCart.ajaxFailure(data, textStats, jqXHR, "add", null);
            }
        }).always(function () {
            loading.hide();
            elem.show();
        });
    },

    removependingorderfromcart: function (url, orderid) {
        $('#cart-message').popover("destroy");
        $.ajax({
            cache: false,
            url: url,
            data: { OrderId: orderid },
            type: 'post',
            success: function (data, textStats, jqXHR) {
                AjaxCart.successprocess(data, textStats, jqXHR, "removeorder");
            },
            error: function (data, textStats, jqXHR) {
                AjaxCart.ajaxFailure(data, textStats, jqXHR, "removeorder");
            }
        }).always(function (data) {
        });
    },

    removeproductfromcart: function (url, productid, element, event) {
        $('#cart-message').popover("destroy");
        if (!element.hasClass("active")) {
            element.addClass("active");
            if (!productid) {
                productid = "all";
                element.closest("table").css("opacity", 0.5);
            } else {
                element.closest("tr").css("opacity", 0.5);
            }

            $.ajax({
                cache: false,
                url: url,
                data: { path: window.location.pathname },
                type: 'post',
                success: function (data, textStats, jqXHR) {
                    AjaxCart.successprocess(data, textStats, jqXHR, "remove", productid, element);
                },
                error: function (data, textStats, jqXHR) {
                    AjaxCart.ajaxFailure(data, textStats, jqXHR, "remove", productid, element);
                }
            }).always(function (data) {
                element.closest("tr").css("opacity", 1);
                element.closest("table").css("opacity", 1);
                element.removeClass("active");
            });
        }
        event.stopPropagation();
        event.preventDefault();
    },

    successprocess: function (response, textStats, jqXHR, type, productid) {
        $(".modal").modal('hide');
        $("html, body").stop().animate({scrollTop: 0});
        if (response.success) {
            AjaxCart.displayPopupNotification(response.title, response.message, "success");
        } else {
            AjaxCart.displayPopupNotification(response.title, response.message, "error");
        }

        // Change float cart item count
        if (productid == null && typeof response.productId != "undefined") {
            productid = response.productId;
        }
        if (response.updateflyoutcartsectionhtml) {
            clearTimeout(cartclosetimeout);
            var cart = $('#flyout-cart');
            var carttable = $(AjaxCart.flyoutcartselector).find(".cart-items tbody");
            // change flyout cart based on action type and item id
            if (type == "removeorder") {
                $(AjaxCart.flyoutcartselector).replaceWith(response.updateflyoutcartsectionhtml);
            } else if (type == "remove") {
                if (productid == "all") {
                    // Remove all items from cart
                    $(AjaxCart.flyoutcartselector).empty().append($('<div />').html(response.updateflyoutcartsectionhtml).find('.mini-shopping-cart'));
                } else {
                    var responsecontent = $('<div />').html(response.updateflyoutcartsectionhtml);
                    if (!responsecontent.find(".cart-items").length) {
                        $(AjaxCart.flyoutcartselector).replaceWith(response.updateflyoutcartsectionhtml);
                    } else if (!responsecontent.find("tr[data-id=" + productid + "]").length) {
                        var itemrows = carttable.find("tr");
                        clearTimeout(carthighlighttimeout);
                        itemrows.removeClass("first last odd even highlight");
                        itemrows.eq(0).addClass("first");
                        itemrows.eq(-1).addClass("last");
                        for (var i = 0; i < itemrows.length; i++) {
                            if (i % 2 == 0) {
                                itemrows.eq(i).addClass("odd");
                            } else {
                                itemrows.eq(i).addClass("even");
                            }
                        }
                        $(".cart-top").replaceWith($('<div />').html(response.updateflyoutcartsectionhtml).find(".cart-top"));
                        $(".cart-bottom").replaceWith($('<div />').html(response.updateflyoutcartsectionhtml).find(".cart-bottom"));
                    }
                }
            } else {
                if (carttable.length) {
                    var itemrow = carttable.find("tr[data-id=" + productid + "]");
                    if (itemrow.length) {
                        itemrow.replaceWith($('<div />').html(response.updateflyoutcartsectionhtml).find("tr[data-id=" + productid + "]"));
                    } else {
                        carttable.append($('<div />').html(response.updateflyoutcartsectionhtml).find("tr[data-id=" + productid + "]"));
                    }
                    var itemrows = carttable.find("tr");
                    clearTimeout(carthighlighttimeout);
                    itemrows.removeClass("first last odd even highlight");
                    itemrows.eq(0).addClass("first");
                    itemrows.eq(-1).addClass("last");
                    for (var i = 0; i < itemrows.length; i++) {
                        if (i % 2 == 0) {
                            itemrows.eq(i).addClass("odd");
                        } else {
                            itemrows.eq(i).addClass("even");
                        }
                    }
                    $(".cart-top").replaceWith($('<div />').html(response.updateflyoutcartsectionhtml).find(".cart-top"));
                    $(".cart-bottom").replaceWith($('<div />').html(response.updateflyoutcartsectionhtml).find(".cart-bottom"));
                } else {
                    $(AjaxCart.flyoutcartselector).replaceWith(response.updateflyoutcartsectionhtml);
                }
                var highlightrow = $('.mini-shopping-cart').find("tr[data-id=" + productid + "]");
                if (highlightrow.length) {
                    highlightrow.addClass("highlight");
                }
            }
        }

        if (response.updatetopcartsectionhtml) {
            var responsenum = parseInt(response.updatetopcartsectionhtml.replace(/[\(\)]/g, ""));
            if (responsenum > 99) {
                responsenum = "!";
            }
        }

        if (response.updatetopwishlisthtml) {
            var responsenum = parseInt(response.updatetopwishlisthtml.replace(/[\(\)]/g, ""));
            if (responsenum > 99) {
                responsenum = "!";
            }
            $(AjaxCart.topwishlistselector).html(responsenum);
        }

        if (typeof response.redirect != "undefined" && response.redirect != "") {
            location.href = response.redirect;
            return true;
        }
        return false;
    },

    ajaxFailure: function (response, textStats, jqXHR, type, productid, element) {
        if (type == "add") {

        } else if (type == "remove") {
            $(AjaxCart.flyoutcartselector).children(".mini-shopping-cart").fadeIn(200);
            $('#flyout-cart').show().stop().animate({ "height": $('.mini-shopping-cart').innerHeight() }, 200);
        }
    },

    displayPopupNotification: function (title, message, type) {
        if (typeof message != "undefined" && message != "") {
            clearTimeout(popoverdestroytimeout);
            var typeclass = " alert-success";
            if (type == "error") {
                typeclass = " alert-danger";
            }
            if ($("header").position().top < 0) {
                $("header").stop().animate({ top: 0 });
            }
            $('#cart-message').popover({
                title: title,
                content: message,
                container: 'header',
                placement: "bottom",
                html: true,
                template: '<div class="popover alert alert-dismissible" role="tooltip"><div class="timer-bar"></div><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'
            }).popover("show");

            $(".popover .timer-bar").stop().animate({ width: 0 }, 5000, "linear");

            var headerHovered = false;

            $(".popover, header").mouseenter(function () {
                headerHovered = true;
                $(".popover .timer-bar").remove();
            }).mouseleave(function () {
                headerHovered = false;
                popoverdestroytimeout = setTimeout(function () {
                    if (!headerHovered) {
                        $('#cart-message').popover("destroy");
                    }
                }, 1500);
            });

            popoverdestroytimeout = setTimeout(function () {
                if (!headerHovered) {
                    $('#cart-message').popover("destroy");
                }
            }, 5000);
        }
    }
};